﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using mshtml;
using SHDocVw;
using MeTalker.SDK.Core;
using MeTalker.Window.SDK.Core;
using MeTalker.Aide.Forms;

namespace MeTalker.Aide
{
    internal delegate void BodyHandler(object sender, MessageBody msgBody);
    internal class TalkerHelper
    {
        IntPtr hwndWin;
        IntPtr hwndText;
        IntPtr hwndWebBrows;
        IntPtr hwndUserMainhWnd;
        ProcInfo proc;
        internal IntPtr HandleWebBrows
        {
            get
            {
                return hwndWebBrows;
            }
        }
        internal IntPtr HandleMessageBody
        {
            get
            {
                return hwndText;
            }
        }
        internal IntPtr HandleWinForm
        {
            get
            {
                return hwndWin;
            }
        }

        public TalkerHelper(ProcInfo proc)
        {
            this.proc = proc;
        }

        public void Init(out IntPtr hwnd)
        {
            Init(proc.Alias, out  hwnd);
        }

        internal static bool Check(string account, out  WindowControl.RECT rect)
        {
            rect = new WindowControl.RECT();
            IntPtr intptr = WindowControl.FindWindow(null, account + UtilHelper.TITLE);
            if (intptr == IntPtr.Zero)
            {
                return false;
            }

            WindowControl.GetWindowRect(intptr, out rect);
            return WindowControl.IsWindowVisible(intptr);
        }

        internal static bool Check(string account)
        {
            IntPtr intptr = WindowControl.FindWindow(null, account + UtilHelper.TITLE);
            if (intptr != IntPtr.Zero && WindowControl.IsWindowVisible(intptr))
            {
                return true;
            }
            return false;
        }


        internal const UInt32 TV_FIRST = 0x4352;
        internal const UInt32 TVGN_ROOT = 0x0000;
        internal const UInt32 TVM_GETNEXTITEM = TV_FIRST + 10;
        internal const UInt32 TVM_SETITEM = TV_FIRST + 13;
        internal const UInt32 WM_USER = 0x0400;
        internal const UInt32 TVM_SELECTITEM = WM_USER + 100;
        IntPtr winIntptrMain;

        internal void Init(string account, out IntPtr hwnd)
        {
            hwnd = IntPtr.Zero;

            hwndWin = WindowControl.FindWindow(null, account + UtilHelper.TITLE);


            IntPtr winIntptr = WindowControl.FindWindowEx(hwndWin, IntPtr.Zero, "StandardWindow", null);
            winIntptr = WindowControl.FindWindowEx(hwndWin, winIntptr, "StandardWindow", null);
            winIntptr = WindowControl.FindWindowEx(hwndWin, winIntptr, "StandardWindow", null);

            winIntptrMain = winIntptr;

            IntPtr winIntptr1 = WindowControl.FindWindowEx(winIntptr, IntPtr.Zero, "SplitterBar", null);

            IntPtr winIntptr5 = WindowControl.FindWindowEx(winIntptr, winIntptr1, "StandardWindow", null);
            IntPtr winIntptr6 = WindowControl.FindWindowEx(winIntptr5, IntPtr.Zero, "StandardWindow", null);
            winIntptr6 = WindowControl.FindWindowEx(winIntptr5, winIntptr6, "StandardWindow", null);

            hwndUserMainhWnd = WindowControl.FindWindowEx(winIntptr5, winIntptr6, "StandardWindow", null);

            IntPtr visibleBrowser = this.FindVisibleSimpleBrowser(hwndUserMainhWnd);

            IntPtr ie = this.FindIEhWnd(visibleBrowser);

            IntPtr winIntptr2 = WindowControl.FindWindowEx(winIntptr1, IntPtr.Zero, "StandardWindow", null);

            IntPtr winIntptrSimp = WindowControl.FindWindowEx(winIntptr2, IntPtr.Zero, "SimpleBrowser", null);
            winIntptrSimp = WindowControl.FindWindowEx(winIntptrSimp, IntPtr.Zero, "Shell Embedding", null);
            winIntptrSimp = WindowControl.FindWindowEx(winIntptrSimp, IntPtr.Zero, "Shell DocObject View", null);
            hwndWebBrows = WindowControl.FindWindowEx(winIntptrSimp, IntPtr.Zero, "Internet Explorer_Server", null);

            IntPtr winIntptr3 = WindowControl.FindWindowEx(winIntptr1, winIntptr2, "StandardWindow", null);

            hwndText = WindowControl.FindWindowEx(winIntptr3, IntPtr.Zero, "RichEditComponent", null);
            hwnd = hwndWin;
            WindowControl.EnumChildWindows(winIntptrMain, FindHwnd, 0);
        }

        #region 事件处理
        //void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        //{
        //    try
        //    {
        //        HtmlElement content = webBrowser.Document.GetElementById("content");
        //        HtmlDocument contentDoc = content.Document;
        //        for (int i = 0; i < content.All.Count; i++)//取出查看DIV标签
        //        {
        //            if (contentDoc.All[i].TagName.ToUpper().Equals("DIV"))
        //            {
        //                if (contentDoc.All[i].Id == "MsgElement")
        //                {
        //                    HandleContent(contentDoc.All[i]);
        //                }
        //            }
        //        }
        //    }
        //    catch { }
        //}




        //void HandleContent(HtmlElement docElement)
        //{
        //    try
        //    {
        //        string sendName = string.Empty;
        //        string sendId = string.Empty;
        //        string msgId = string.Empty;
        //        string msgTime = string.Empty;
        //        string senderSite = string.Empty;
        //        string content = string.Empty;
        //        for (int i = 0; i < docElement.All.Count; i++)//取出查看DIV标签
        //        {
        //            if (docElement.All[i].TagName.ToUpper().Equals("SPAN"))
        //            {
        //                if (docElement.All[i].Id == "SenderName")
        //                {
        //                    sendName = docElement.All[i].InnerText;
        //                }
        //                else if (docElement.All[i].Id == "MsgTime")
        //                {
        //                    msgTime = docElement.All[i].InnerText;
        //                    if (!string.IsNullOrEmpty(msgTime) && msgTime.Length > 9)
        //                    {
        //                        msgTime = msgTime.Substring(1, 8);
        //                    }
        //                }
        //                else if (docElement.All[i].Id == "SenderSite")
        //                {
        //                    senderSite = docElement.All[i].InnerText;
        //                }
        //            }

        //            if (docElement.All[i].TagName.ToUpper().Equals("DIV"))
        //            {
        //                if (docElement.All[i].Id == "MsgContent")
        //                {
        //                    sendId = docElement.All[i].Children[0].GetAttribute("SendID");
        //                    msgId = docElement.All[i].Children[0].GetAttribute("msgId");
        //                    string id = docElement.All[i].Children[0].GetAttribute("id");
        //                    content = HandlerImgContent(docElement.All[i].Children[0], id);
        //                }
        //            }
        //        }

        //        if (caches != null && !caches.ContainsKey(msgTime))
        //        {
        //            MessageBody msgbody = new MessageBody();
        //            msgbody.Content = content;
        //            msgbody.SenderSite = senderSite;
        //            msgbody.SendId = sendId;
        //            msgbody.SendName = sendName;
        //            msgbody.MsgId = msgId;
        //            msgbody.MsgTime = msgTime;
        //            caches.Add(msgTime, msgbody);
        //            if (MessageBodyHandler != null)
        //                MessageBodyHandler.BeginInvoke(this, msgbody, null, null);
        //            //Console.WriteLine("当前数" + caches.Count);
        //        }
        //    }
        //    catch { }
        //}

        //string HandlerImgContent(HtmlElement docElement,string id)
        //{
        //    try
        //    {
        //        string msgs = string.Empty;
        //        for (int i = 0; i < docElement.All.Count; i++)//取出查看DIV标签
        //        {
        //            if (docElement.All[i].TagName.ToUpper().Equals("IMG"))
        //            {
        //                string alt = docElement.All[i].GetAttribute("alt");
        //                if (!string.IsNullOrEmpty(alt))
        //                {
        //                    msgs += alt.Split(' ')[0];
        //                }
        //            }

        //            if (docElement.All[i].TagName.ToUpper().Equals("FONT"))
        //            {
        //                msgs += docElement.All[i].InnerText;
        //            }
        //        }
        //        return msgs;
        //    }
        //    catch { return ""; }
        //}
        #endregion
        IntPtr FindVisibleSimpleBrowser(IntPtr root)
        {
            bool flag = true;
            IntPtr winIntptr5 = WindowControl.FindWindowEx(root, IntPtr.Zero, "SimpleBrowser", null);
            if (WindowControl.IsWindowVisible(winIntptr5))
            {
                return winIntptr5;
            }
            IntPtr hWndWebBrows = IntPtr.Zero;
            do
            {
                winIntptr5 = WindowControl.FindWindowEx(root, winIntptr5, "SimpleBrowser", null);
                flag = WindowControl.IsWindowVisible(winIntptr5);
                if (flag)
                    hWndWebBrows = winIntptr5;
            } while (flag);
            return hWndWebBrows;
        }

        IntPtr FindIEhWnd(IntPtr hWnd)
        {
            hWnd = WindowControl.FindWindowEx(hWnd, IntPtr.Zero, "Shell Embedding", null);
            hWnd = WindowControl.FindWindowEx(hWnd, IntPtr.Zero, "Shell DocObject View", null);
            return WindowControl.FindWindowEx(hWnd, IntPtr.Zero, "Internet Explorer_Server", null);
        }

        IntPtr useBrowserIntptr;

        bool FindHwnd(IntPtr hwnd, int a)
        {
            StringBuilder builder = new StringBuilder(0x100);
            WindowControl.GetClassName(hwnd, builder, 0x100);

            if (builder.ToString().Equals("SimpleBrowser"))
            {
                if (WindowControl.IsWindowVisible(hwnd))
                {
                    IntPtr briwser = WindowControl.FindWindowEx(WindowControl.FindWindowEx(WindowControl.FindWindowEx(hwnd, IntPtr.Zero, "Shell Embedding", null), IntPtr.Zero, "Shell DocObject View", null), IntPtr.Zero, "Internet Explorer_Server", null);
                    if (briwser != hwndWebBrows)
                    {
                        lock (this)
                        {
                            useBrowserIntptr = briwser;
                            hwndUserMainhWnd = useBrowserIntptr;
                        }
                        return false;
                    }

                }
            }
            return true;
        }

        string GetCustomName(string html) {

            if (html.Equals(userHtml)) return userName;

            //lock (this)
            //{
                HTMLDocumentClass oc = new HTMLDocumentClass();
                IHTMLDocument2 doc2 = oc;
                doc2.designMode = "on";
                doc2.write(html);
                IHTMLElementCollection htmlelments = oc.getElementsByTagName("DT");
                foreach (var d in htmlelments)
                {
                    HTMLDTElementClass dt = d as HTMLDTElementClass;
                    if (dt == null) continue;
                    IHTMLElementCollection athors = dt.getElementsByTagName("A");
                    foreach (var tmp in athors)
                    {
                        HTMLAnchorElementClass tmpAuthor = tmp as HTMLAnchorElementClass;
                        if (tmpAuthor != null)
                        {
                            userHtml = html;
                            userName = tmpAuthor.innerText;
                            return userName;
                        }
                    }
                }
                return userName;
            //}
        }
        string userName;
        string userHtml;
        internal string HandlerSelectUserMessage()
        {
            try
            {
                string html;
                string text;
                LibHelper.GetMessage(hwndUserMainhWnd, out text, out html);
                try
                {
                    try
                    {
                        if (!string.IsNullOrEmpty(text))
                        {
                        string userName = GetCustomName( html);
                        if (!string.IsNullOrEmpty(userName)) return userName;
                            string[] msgs = text.Split(new char[] { '\r', '\n' });
                            foreach (string str in msgs)
                            {
                                if (str.Contains("会员信息"))
                                {
                                    int index = str.IndexOf("会员信息");
                                    return str.Substring(index + 4).Trim();
                                }
                            }
                            string msg = text.Split(new char[] { '\r', '\n' })[0].Trim();
                            if (!string.IsNullOrEmpty(msg))
                                return msg;
                        }
                    }
                    catch { }
                    try
                    {
                        if (!string.IsNullOrEmpty(html))
                        {
                            return html.Substring(html.IndexOf("nick") + 5, html.IndexOf("&amp;") - html.IndexOf("nick") - 5);
                        }
                    }
                    catch { }
                }
                finally
                {
                    WindowControl.EnumChildWindows(winIntptrMain, FindHwnd, 0);
                }
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("HandlerSelectUserMessage", ex);
            }
            return "";
        }
        internal string GetEditMessage()
        {
            StringBuilder sb = new StringBuilder(1234);
            KeysetControl.SendMessage(this.HandleMessageBody, (uint)KeysetControl.WM_GETTEXT, 255, sb);
            return sb.ToString();
        }

        internal string GetMessageText()
        {
            return LibHelper.GetMessageText(hwndWebBrows);
        }

        internal string HandlerResponseMessage()
        {
            try
            {
                return LibHelper.GetMessageWinHtml(hwndWebBrows);
            }
            catch (Exception ex)
            {
                if (UtilHelper.DEBUG)
                    MuchInfo.Logs.MILog.Debug("HandlerResponseMessage", ex);
            }
            return "";
        }

        internal void SetForegroundMainWindow(IntPtr hwnd)
        {
            WindowControl.SetForegroundWindow(hwnd);
        }

        internal void SetForegroundMainWindow()
        {
            SetForegroundMainWindow(hwndWin);
        }

        internal bool MainRect(IntPtr hwnd, out WindowControl.RECT rect)
        {
            return WindowControl.GetWindowRect(hwnd, out rect);
        }

        internal bool MainRect(out WindowControl.RECT rect)
        {
            return MainRect(hwndWin, out rect);
        }

        internal void SendText(string msg)
        {
            SendText(hwndText, msg);
        }

        internal void SendText(IntPtr intptr, string msg)
        {
            WangHepler.Send(HandleWinForm, intptr, msg, false);
            WindowControl.PostMessage(intptr, 256, 32, 0);
            KeysetControl.keybd_event(13, 0, 0, 0);
        }

        internal void SetText(string msg)
        {
            SetText(hwndText, msg);
        }

        internal void SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam)
        {
            KeysetControl.SendMessage(hwnd, wMsg, wParam, lParam);
        }

        internal void SetText(IntPtr intptr, string msg)
        {
            WangHepler.Send(HandleWinForm, intptr, msg, false);
            WindowControl.PostMessage(intptr, 256, 32, 0);
        }
    }
}